package com.canal.admin.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * body体登录过滤器
 * @author Administrator
 * @description
 * @date 2019年03月16 11:56
 */
public class LoginUserPasswordBodyFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 构造函数，指明该过滤器用户登录接口
     */
    public LoginUserPasswordBodyFilter() {
        super(new AntPathRequestMatcher("/login","POST"));
    }

    @Override
    public void afterPropertiesSet() {
        Assert.notNull(getAuthenticationManager(), "authenticationManager must be specified");
        Assert.notNull(getSuccessHandler(), "successHandler must be specified");
        Assert.notNull(getFailureHandler(), "failureHandler must be specified");

    }

    /**
     * 执行果过滤
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        String username;
        String password;
        String body = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
        if(StringUtils.hasText(body)) {
            JSONObject jsonObject = JSONObject.parseObject(body);
            username = (String) jsonObject.get("username");
            password = (String) jsonObject.get("password");
        } else {
            username = "";
            password = "";
        }
        username = username.trim();
        Authentication authentication = new UsernamePasswordAuthenticationToken(username,password);
        return getAuthenticationManager().authenticate(authentication);
    }
}
